<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户签到最大连续签到数
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300030_000040_t_signin_record_continue extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_signin}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $this->update($this->tableName, ['serial' => 0]);
        $query = (new Query())->from($this->tableName);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->update($this->tableName, ['serial' => 0]);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $query = (new Query())->from('{{%user_signin_log}}');
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            $max = $query->where(['user_id' => $row['user_id']])->max('serial');
            $connect->update($migration->tableName, ['serial' => $max], [
                'user_id' => $row['user_id']
            ])->execute();
        }
    }

}
